/*
 * Copyright 2015-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dcp.jeedcp.modules.report.web.datasource;

import com.dcp.jeedcp.common.config.Global;
import com.dcp.jeedcp.common.persistence.Page;
import com.dcp.jeedcp.common.utils.DateUtils;
import com.dcp.jeedcp.common.utils.MyBeanUtils;
import com.dcp.jeedcp.common.utils.StringUtils;
import com.dcp.jeedcp.common.utils.excel.ExportExcel;
import com.dcp.jeedcp.common.utils.excel.ImportExcel;
import com.dcp.jeedcp.common.web.BaseController;
import com.dcp.jeedcp.common.web.JsonResult;
import com.dcp.jeedcp.modules.report.entity.datasource.Datasource;
import com.dcp.jeedcp.modules.report.service.datasource.DatasourceService;
import com.google.common.collect.Lists;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 数据源设置Controller
 * @author henry
 * @version 2017-05-12
 */
@Controller
@RequestMapping(value = "${adminPath}/report/datasource/datasource")
public class DatasourceController extends BaseController {

	@Autowired
	private DatasourceService datasourceService;
	
	@ModelAttribute
	public Datasource get(@RequestParam(required=false) String id) {
		Datasource entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = datasourceService.get(id);
		}
		if (entity == null){
			entity = new Datasource();
		}
		return entity;
	}
	@RequestMapping(value = "/listAll")
	@ResponseBody
	public List<Datasource> listAll() {
		return datasourceService.findAll();
	}
	/**
	 * 数据源设置列表页面
	 */
	@RequiresPermissions("report:datasource:datasource:list")
	@RequestMapping(value = {"list", ""})
	public String list(Datasource datasource, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Datasource> page = datasourceService.findPage(new Page<Datasource>(request, response), datasource); 
		model.addAttribute("page", page);
		return "modules/report/datasource/datasourceList";
	}

	/**
	 * 查看，增加，编辑数据源设置表单页面
	 */
	@RequiresPermissions(value={"report:datasource:datasource:view","report:datasource:datasource:add","report:datasource:datasource:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Datasource datasource, Model model) {
		model.addAttribute("datasource", datasource);
		return "modules/report/datasource/datasourceForm";
	}

	/**
	 * 保存数据源设置
	 */
	@RequiresPermissions(value={"report:datasource:datasource:add","report:datasource:datasource:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Datasource datasource, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, datasource)){
			return form(datasource, model);
		}
		String driverClass =   "com.mysql.jdbc.Driver";
		String queryerClass =   "com.easytoolsoft.easyreport.engine.query.MySqlQueryer";
		String option ="{\"initialSize\":3,\"maxActive\":20,\"minIdle\":1,\"maxWait\":60000,\"timeBetweenEvictionRunsMillis\":60000,\"minEvictableIdleTimeMillis\":300000,\"testWhileIdle\":true,\"testOnBorrow\":false,\"testOnReturn\":false,\"maxOpenPreparedStatements\":20,\"removeAbandoned\":true,\"removeAbandonedTimeout\":1800,\"logAbandoned\":true}";
		if(!datasource.getIsNewRecord()){//编辑表单保存

			Datasource t = datasourceService.get(datasource.getId());//从数据库取出记录的值
			t.setDriverClass(driverClass);
			t.setQueryerClass(queryerClass);
			MyBeanUtils.copyBeanNotNull2Bean(datasource, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			datasourceService.save(t);//保存
		}else{//新增表单保存
			datasource.setDriverClass(driverClass);
			datasource.setQueryerClass(queryerClass);
			datasource.setOptions(option);
			datasourceService.save(datasource);//保存
		}
		addMessage(redirectAttributes, "保存数据源设置成功");
		return "redirect:"+Global.getAdminPath()+"/report/datasource/datasource";
	}
	
	/**
	 * 删除数据源设置
	 */
	@RequiresPermissions("report:datasource:datasource:del")
	@RequestMapping(value = "delete")
	public String delete(Datasource datasource, RedirectAttributes redirectAttributes) {
		datasourceService.delete(datasource);
		addMessage(redirectAttributes, "删除数据源设置成功");
		return "redirect:"+Global.getAdminPath()+"/report/datasource/datasource";
	}
	
	/**
	 * 批量删除数据源设置
	 */
	@RequiresPermissions("report:datasource:datasource:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			datasourceService.delete(datasourceService.get(id));
		}
		addMessage(redirectAttributes, "删除数据源设置成功");
		return "redirect:"+Global.getAdminPath()+"/report/datasource/datasource";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("report:datasource:datasource:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Datasource datasource, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "数据源设置"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Datasource> page = datasourceService.findPage(new Page<Datasource>(request, response, -1), datasource);
    		new ExportExcel("数据源设置", Datasource.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出数据源设置记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/report/datasource/datasource";
    }

	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("report:datasource:datasource:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Datasource> list = ei.getDataList(Datasource.class);
			for (Datasource datasource : list){
				try{
					datasourceService.save(datasource);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条数据源设置记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条数据源设置记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入数据源设置失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/report/datasource/datasource";
    }
	
	/**
	 * 下载导入数据源设置数据模板
	 */
	@RequiresPermissions("report:datasource:datasource:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "数据源设置数据导入模板.xlsx";
    		List<Datasource> list = Lists.newArrayList(); 
    		new ExportExcel("数据源设置数据", Datasource.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/report/datasource/datasource";
    }

	//测试数据源
	@RequestMapping(value = "/testConnection",produces = "application/json;charset=utf-8")
	@ResponseBody
	public JsonResult testConnection(String url, String pass, String user) {
		JsonResult<String> result = new JsonResult<>();
		String driverClass =   "com.mysql.jdbc.Driver";
		result.setSuccess(datasourceService.testConnection(driverClass, url, user, pass));
		return result;
	}
	//测试数据源
	@RequestMapping(value = "/testConnectionById")
    @ResponseBody
	public JsonResult testConnection(String id) {
		JsonResult<String> result = new JsonResult<>();
		Datasource dsPo =datasourceService.get(id);
		result.setSuccess(datasourceService.testConnection(
				dsPo.getDriverClass(),
				dsPo.getJdbcUrl(),
				dsPo.getUser(), dsPo.getPassword()));
		return result;
	}



}